import { createSlice } from "@reduxjs/toolkit";
import { imageAPI, imgApi } from "@/apis/images";

const iamgesSlice = createSlice({
  name: "image",
  initialState: {
    items: [],
    item: [],
    loading: false,
    error: null,
  },
  reducers: {
    fetchImageStart(state) {
      state.loading = true;
      state.error = null;
    },
    fetImgItem(state, action) {
      state.item = action.payload;
      state.loading = false;
    },
    fetchImageSuccess(state, action) {
      state.items = action.payload;
      state.loading = false;
    },
    fetchImageFailure(state, action) {
      state.error = action.payload;
      state.loading = false;
    },
  },
});

export const {
  fetchImageStart,
  fetchImageSuccess,
  fetchImageFailure,
  fetImgItem,
} = iamgesSlice.actions;

export const fetchImgItems = () => async (dispatch) => {
  dispatch(fetchImageStart());
  const res = await imageAPI();
  dispatch(fetchImageSuccess(res.data));
};

export const getImgItem = () => async (dispatch) => {
  dispatch(fetchImageStart());
  const res = await imgApi();
  dispatch(fetImgItem(res.data));
};

export default iamgesSlice.reducer;
